package com.ugoodtech.mdcc.web.service.impl;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

import com.google.common.collect.Lists;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.QUser;
import com.ugoodtech.mdcc.core.domain.QUserProfile;
import com.ugoodtech.mdcc.core.domain.Role;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.domain.UserType;
import com.ugoodtech.mdcc.core.exception.UsernameAlreadyExistException;
import com.ugoodtech.mdcc.core.exception.VStarException;
import com.ugoodtech.mdcc.core.repository.RoleRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.web.pojo.vo.UserProfileDTO;
import com.ugoodtech.mdcc.web.service.UserProfileService;
import com.ugoodtech.mdcc.web.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Override
    public User createUser(User user, Long roleId) throws UsernameAlreadyExistException {
        if (userRepository.findByUsername(user.getUsername()) != null) {
            throw new UsernameAlreadyExistException();
        }
        user.setCreationTime(new Date());
        user.setAccountExpired(false);
        user.setAccountLocked(false);
        user.setCredentialsExpired(false);
        user.setEnabled(true);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //
        //
        if(roleId!=null){
            Role role=roleRepository.findOne(roleId);
        }
        return userRepository.save(user);
    }

    @Override
    public void updateUser(User user, Long enterpriseId) throws UsernameAlreadyExistException {
        User existUser = userRepository.findOne(user.getId());
        boolean usernameChanged = !existUser.getUsername().equals(user.getUsername());
        if (usernameChanged && userRepository.findByUsername(user.getUsername()) != null) {
            throw new UsernameAlreadyExistException();
        }
        if (!"".equals(user.getPassword()) && null != user.getPassword()) {
            existUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        existUser.setUsername(user.getUsername());
        
        userRepository.save(existUser);
    }


    @Override
    public Page<User> queryUser(String param, String roleName, Pageable pageable) {
        QUser qUser = QUser.user;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUser.deleted.eq(false));

        if (!StringUtils.isEmpty(param)) {
            BooleanBuilder keyBuilder = new BooleanBuilder();

            builder.and(
                    keyBuilder.or(qUser.username.like("%" + param + "%"))
                            .or(qUser.openId.like("%" + param + "%"))
            );
        }
        return userRepository.findAll(builder, pageable);
    }

    @Override
    public User queryOneUser(String userNo, String name) throws VStarException {
       UserProfile userProfile = userProfileService.queryOneUserProfile(userNo,name);
        return userProfile.getUser();
    }

    @Override
    public void delete(Long userId) {
        userRepository.delete(userId);
    }

    @Override
    public void delete(List<Long> userIds) {
        userRepository.delete(userIds);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("user not found by the username:" + username);
        }
        return user;
    }

    @Override
    public boolean changePassword(User user, String password, String oldPassword) {
        if (passwordEncoder.matches(oldPassword, user.getPassword())) {
            User savedUser = userRepository.findByUsername(user.getUsername());
            savedUser.setPassword(passwordEncoder.encode(password));
            userRepository.save(savedUser);
//            log.info("系统用户的密码已经修改为"+password);
//            System.out.println(user.getPassword());
            return true;
        } else {
            return false;
        }
        //if old password do not match,then return

    }

    @Override
    public boolean initPassword(User user) {
        User savedUser = userRepository.findByUsername(user.getUsername());
        savedUser.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
        userRepository.save(savedUser);
        return true;
    }
    @Override
    public List<String> getUserNameListOfEmployee(String name) {
        List<String> userNameList = new ArrayList<>();
        BooleanBuilder booleanBuilder =new BooleanBuilder();
        QUserProfile qUserProfile = QUserProfile.userProfile;
        booleanBuilder.and(qUserProfile.realName.like('%' + name + '%')).
                and(qUserProfile.user.userType.in(Arrays.asList(UserType.dealers, UserType.insiders)));
//        UserProfileDOExample example = new UserProfileDOExample();
//        example.or().andUsernameLike('%' + name + '%').andIsDeletedEqualTo(0)
//                .andIdentityIn(Arrays.asList(User.DEALER, User.IS_EMPLOYEE));

        List<UserProfile> userProfileDOList =Lists.newArrayList(userProfileRepository.findAll(booleanBuilder));
        for (UserProfile userProfileDO : userProfileDOList) {
            if (null != userProfileDO.getRealName()) {
                userNameList.add(userProfileDO.getRealName());
            }
        }
        return userNameList;
    }
}
